package com.yuke.cloud.service.omc.config;


import com.alibaba.fastjson.JSON;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.controller.frontend.OdsPointsController;
import com.yuke.cloud.service.omc.controller.frontend.OdsTeamController;
import com.yuke.cloud.service.omc.dto.OdsPointsDto;
import com.yuke.cloud.service.omc.entity.*;
import com.yuke.cloud.service.omc.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
public class KeyExpiredListener implements MessageListener {
    @Resource
    private OdsOrderService odsOrderService;
    @Resource
    private OdsOrderGoodsService odsOrderGoodsService;
    @Resource
    private OdsTeamIntentService odsTeamIntentService;
    @Resource
    private OdsBillService odsBillService;
    @Resource
    private OdsPointsService odsPointsService;
    @Autowired
    private OdsStockOrderService odsStockOrderService;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private CmcFeignApi cmcFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private OdsPointsController odsPointsController;
    @Resource
    private OdsTeamService odsTeamService;
    @Resource
    private OdsTeamController odsTeamController;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.err.println("redis key有过期的" + message);

        //先判断是不是订单过期事件，别的不管。

        if (message.toString().contains("zero")) {
            //订单过期未支付则修改状态为已经取消

            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long aLong = Long.valueOf(s1);
            System.err.println("客户订单有过期的zero orderId="+aLong);
            //20191024加入判断,支付状态为1，已支付的
            OdsOrder odsOrder = odsOrderService.findById(aLong);
            if(odsOrder!=null){
               if (odsOrder.getPayStatus().toString().equals("1")){
                   return;
               }

            }
            odsOrder.setOrderId(aLong);
            odsOrder.setOrderStatus((byte)3);
            odsOrderService.update(odsOrder);

            //优惠券处理
            Long couponReceiveId = cmcFeignApi.findCouponReceiveIdByOrderId(aLong);
            if (couponReceiveId>0){
                cmcFeignApi.updateCouponReceiveBack(couponReceiveId);
            }
            //积分处理
            if (odsOrder.getPayType().toString().equals("6") || odsOrder.getPayType().toString().equals("7")){
                OdsPoints odsPoints = new OdsPoints();
                odsPoints.setUserId(odsOrder.getUserId());
                odsPoints.setOrderId(odsOrder.getOrderId().toString());
                List<OdsPoints> odsPointsList = odsPointsService.select(odsPoints);
                if (odsPointsList != null && odsPointsList.size() > 0){
                    OdsPointsDto odsPointsDto = new OdsPointsDto();
                    odsPointsDto.setNumber(odsPointsList.get(0).getNumber());
                    odsPointsDto.setUserId(odsOrder.getUserId());
                    odsPointsDto.setOrderId(odsOrder.getOrderId().toString());
                    odsPointsDto.setPointAspect((byte)1);
                    odsPointsDto.setPointType((byte)8);
                    //返还积分
                    odsPointsController.addSignIn(odsPointsDto);
                }
            }

            OdsOrder byId = odsOrderService.findById(aLong);
            Long shopId = byId.getShopId();
            OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
            odsOrderGoods.setOrderId(aLong);
            List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
//            List<Map> list = new ArrayList<>();
            List<Map> list1 = new ArrayList<>();

            // add by wg 20190605 判断秒杀商品
            List<CmsSecKillSkuDto> cmsSecKillSkuDtos = odsOrderService.getSecKillSkus();

            for (int i = 0; i < select.size(); i++) {
//                Map map = new HashMap<>();
                Map map1 = new HashMap<>();
                OdsOrderGoods odsOrderGoods1 = select.get(i);
//                map.put("shopId", shopId);
//                map.put("specId", odsOrderGoods1.getSpecId());
                map1.put("shopId", shopId);
                map1.put("specId", odsOrderGoods1.getSpecId());
                Integer goodsNum = odsOrderGoods1.getGoodsNum();
//                map.put("goodsNum", goodsNum);
                map1.put("goodsNum",-goodsNum);
                map1.put("isFactory", byId.getIsFactory()); // 用户下单的商品有可能是厂家直销的商品
                map1.put("warehouseId", byId.getWarehouseId());  // add by wg 20190727
//                list.add(map);
                list1.add(map1);

                // add by wg 20190605 判断秒杀商品
                // todo 从redis中获取活动商品并判断用户是否已经超买,暂时不做购买限制
                for (CmsSecKillSkuDto cmsSecKillSkuDto : cmsSecKillSkuDtos) {
                    if (cmsSecKillSkuDto.getSpecId().longValue() == odsOrderGoods1.getSpecId().longValue()) {
                        cmsSecKillSkuDto.setStoreCount(cmsSecKillSkuDto.getStoreCount());
                        cmsSecKillSkuDto.setLockCount(cmsSecKillSkuDto.getLockCount()-goodsNum);
                        cmsSecKillSkuDto.setSaledCount(cmsSecKillSkuDto.getSaledCount()-goodsNum);
                    }
                }
            }
//            String s = JSON.toJSONString(list);
            String s3 = JSON.toJSONString(list1);
            wmcStorageFeignApi.preadd(s3);
//            smcFeignApi.updateStockCount(s); // V1.1版没有店铺线上库存

            // 针对秒杀商品进行库存恢复
            // add by wg 20190605 秒杀商品库存锁定
            if (cmsSecKillSkuDtos != null && cmsSecKillSkuDtos.size() > 0) {
                cmcFeignApi.updateSecKillSkusCount(cmsSecKillSkuDtos);
            }

        } else if (message.toString().contains("second")){

            System.err.println("店铺订单有过期的,不需要发货的未支付");
            String[] split = message.toString().split(":");
            String s1 = split[1];
            OdsStockOrder odsStockOrder = new OdsStockOrder();
            Long aLong = Long.valueOf(s1);
            odsStockOrder.setStockOrderId(aLong);
            odsStockOrder.setPayStatus((byte)0);
            odsStockOrder.setStockStatus((byte)3);
            odsStockOrderService.update(odsStockOrder);
        } else if(message.toString().contains("first")){ //店铺下单,线上支付的
            //20200812 不取消订单了。
            if (message != null){
                return;
            }
            //商品下单，需要发货，以为之前预定了现在要取消预定
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long aLong = Long.valueOf(s1);

            //20191024加入判断,支付状态为1，已支付的
            OdsOrder odsOrder = odsOrderService.findById(aLong);
            if(odsOrder!=null){
                if (odsOrder.getPayStatus().toString().equals("1")){
                    return;
                }
                //20200807 支付方式为货到付款的，不取消订单状态
                if(odsOrder.getPayType().toString().equals("0")){
                    return;
                }
            }
            odsOrder.setOrderId(aLong);
            odsOrder.setOrderStatus((byte)3);
            odsOrderService.update(odsOrder);
            //优惠券处理
            Long couponReceiveId = cmcFeignApi.findCouponReceiveIdByOrderId(aLong);
            if (couponReceiveId>0){
                cmcFeignApi.updateCouponReceiveBack(couponReceiveId);
            }

            OdsOrder byId = odsOrderService.findById(aLong);
            OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
            odsOrderGoods.setOrderId(aLong);
            List<OdsOrderGoods> select = odsOrderGoodsService.select(odsOrderGoods);
            List<Map> list = new ArrayList<>();
            for (int i = 0; i < select.size(); i++) {
                Map map = new HashMap<>();
                OdsOrderGoods odsOrderGoods1 = select.get(i);
                map.put("shopId", byId.getShopId());
                map.put("specId", odsOrderGoods1.getSpecId());
                Integer goodsNum = odsOrderGoods1.getGoodsNum();
                //预定仓库货品，数量减少，所以goodsNum是正数
                map.put("goodsNum",-goodsNum);
                map.put("warehouseId", byId.getWarehouseId());  // add by wg 20190727
                list.add(map);
            }
            String s = JSON.toJSONString(list);
            wmcStorageFeignApi.preadd(s);
        }else  if(message.toString().contains("recharge")){
            //充值
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long billId = Long.valueOf(s1);
            OdsBill odsBill = odsBillService.findById(billId);
            if (odsBill != null){
                odsBill.setBalanceType((byte)2);
                odsBillService.update(odsBill);

            }

        }else if(message.toString().contains("CouponReceiveIdAndOrderId")){
            //优惠券返还
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long orderId = Long.valueOf(s1);
            //todo 找到使用该优惠券的订单，当该订单被取消，还原优惠券状态
            Long couponReceiveId = cmcFeignApi.findCouponReceiveIdByOrderId(orderId);
            if (couponReceiveId > 0){
                OdsOrder odsOrder = odsOrderService.findById(orderId);
                if (odsOrder.getOrderStatus() > 2){
                    cmcFeignApi.updateCouponReceiveBack(couponReceiveId);
                }

                log.error("有redis保存的优惠券状态过期couponReceiveId={},orderId={}",couponReceiveId,orderId);
            }

         }else  if(message.toString().contains("teamIntent")){
            //拼单购支付过期
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long intentId = Long.valueOf(s1);
            OdsTeamIntent odsTeamIntent = odsTeamIntentService.findById(intentId);
            if (odsTeamIntent != null){
                odsTeamIntent.setIntentStatus((byte)3);
                odsTeamIntentService.update(odsTeamIntent);

            }

        }else  if(message.toString().contains("TeamShareInfo")){
            //拼单团到期
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long teamId = Long.valueOf(s1);
            OdsTeam odsTeam = odsTeamService.findById(teamId);
            if (odsTeam != null){
                //改变拼单团状态，取消状态
                odsTeam.setTeamStatus((byte)4);
                odsTeamService.update(odsTeam);
                //改变拼单订单状态\退款
                odsTeamController.refoundTeam(teamId);
            }

        }else  if(message.toString().contains("TeamInfo")){
            //团到期
            String[] split = message.toString().split(":");
            String s1 = split[1];
            Long teamId = Long.valueOf(s1);
            OdsTeam odsTeam = odsTeamService.findById(teamId);
            if (odsTeam != null){
                Integer sumMoney = 0;
                Integer countIntent = 0;


                //统计团订单金额，录入到团信息中
                OdsTeamIntent odsIntent = new OdsTeamIntent();
                odsIntent.setTeamId(teamId);
                List<OdsTeamIntent> odsTeamIntentList = odsTeamIntentService.select(odsIntent);
                if (odsTeamIntentList != null && odsTeamIntentList.size() > 0){

                    for (OdsTeamIntent intent : odsTeamIntentList){
                        //订单状态已确认，支付状态已支付
                        if (intent.getIntentStatus().equals((byte)1) && intent.getPayStatus().equals((byte)1)){
                            sumMoney += intent.getAmountPaid();
                            countIntent++;

                            //改变团订单状态,已成团，备货中
                            intent.setIntentStatus((byte)2);
                            intent.setShippingStatus((byte)1);
                            odsTeamIntentService.update(intent);
                        }
                    }


                }

                //改变团状态，成功
                Date todayTime = new Date();
                odsTeam.setTeamStatus((byte)2);
                odsTeam.setFinishNum(countIntent);
                odsTeam.setFinishMoney(sumMoney);
                odsTeam.setFinishTime(todayTime);
                odsTeamService.update(odsTeam);

                //如果店铺设置为开启状态，自动开启下一期团
                List<ShopInfoDto> list = smcFeignApi.getShopInfoDtoByUserId(odsTeam.getUserId());
                if (list != null || list.size() > 0){
                    if (list.get(0).getRunStatus().equals((byte)2)){
                        return;
                    }
                }
                odsTeam.setTeamId(null);
                odsTeam.setTeamNo(null);
                odsTeam.setTeamStatus((byte)0);
                odsTeam.setFinishMoney(0);
                odsTeam.setFinishNum(0);
                odsTeam.setFinishTime(null);
                odsTeam.setBeginTime(todayTime);

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(odsTeam.getEndTime());
                calendar.add(Calendar.DATE,+1);
                odsTeam.setEndTime(calendar.getTime());
                odsTeam.setStartTime(todayTime);
                odsTeamController.add(odsTeam);

            }

        }
    }
}
